package persistent

import (
	"context"
	"time"

	"gitee.com/leonscript/sally/v2/domain/aggregate"
	"gitee.com/leonscript/sally/v2/domain/entity"
	"gorm.io/gorm"
)

type NodeReviewTaskClient struct {
	db *gorm.DB `name:"saas_db"`
}

func NewNodeReviewTaskClient(db *gorm.DB) *NodeReviewTaskClient {
	return &NodeReviewTaskClient{db: db}
}

// QueryNodeReviewTasks 查询节点审批任务列表
// 支持按审批人、业务代码、业务ID、工作流ID、工作流名称、创建时间范围、表单内容等条件进行查询
func (w *NodeReviewTaskClient) QueryNodeReviewTasks(ctx context.Context, req aggregate.GetNodeReviewTasksRequest) (result []NodeReviewTasks, total int64, err error) {
	// 构建基础查询，先应用Scopes设置表和JOIN关系
	db := w.db.WithContext(ctx).Scopes(NodeReviewerTaskView).Where("node_reviewer_task.status != ?", entity.TaskArchivedStatus)

	if req.ReviewerID != "" {
		db = db.Where("node_reviewer_task.reviewer_id = ?", req.ReviewerID)
	}

	if len(req.Statuses) > 0 {
		db = db.Where("node_reviewer_task.status IN ?", req.Statuses)
	}

	if req.BusinessCode != "" {
		db = db.Where("workflow.business_code = ?", req.BusinessCode)
	}

	if req.BusinessID != "" {
		db = db.Where("workflow.business_id = ?", req.BusinessID)
	}

	if req.WorkflowID != "" {
		db = db.Where("workflow.id = ?", req.WorkflowID)
	}

	if req.WorkflowName != "" {
		db = db.Where("workflow_template.name LIKE ?", "%"+req.WorkflowName+"%")
	}

	if !req.CreatedAtStart.IsZero() {
		db = db.Where("node_reviewer_task.created_at >= ?", req.CreatedAtStart)
	}

	if !req.CreatedAtEnd.IsZero() {
		db = db.Where("node_reviewer_task.created_at <= ?", req.CreatedAtEnd)
	}

	if req.FormContentSearch != "" {
		db = db.Where("JSON_SEARCH(workflow.form_content, 'one', ?) IS NOT NULL", "%"+req.FormContentSearch+"%")
	}

	if req.NodeID != "" {
		db = db.Where("node.id = ?", req.NodeID)
	}

	if req.WorkflowCreateUser != "" {
		db = db.Where("workflow.create_user = ?", req.WorkflowCreateUser)
	}

	if !req.WorkflowCreatedAtStart.IsZero() {
		db = db.Where("workflow.created_at >= ?", req.WorkflowCreatedAtStart)
	}

	if !req.WorkflowCreatedAtEnd.IsZero() {
		db = db.Where("workflow.created_at <= ?", req.WorkflowCreatedAtEnd)
	}

	if req.WorkflowBusinessParams != nil {
		db = req.WorkflowBusinessParams.WithGormCondition(db)
	}

	if req.WorkflowStatus > 0 {
		db = db.Where("workflow.status = ?", req.WorkflowStatus)
	}

	if req.WorkflowSponsorID != "" {
		db = db.Where("workflow.sponsor_id = ?", req.WorkflowSponsorID)
	}

	if !req.UpdatedAtStart.IsZero() {
		db = db.Where("node_reviewer_task.updated_at >= ?", req.UpdatedAtStart)
	}

	if !req.UpdatedAtEnd.IsZero() {
		db = db.Where("node_reviewer_task.updated_at <= ?", req.UpdatedAtEnd)
	}

	// 分页处理：先统计总数，再应用分页
	if !req.NoPage {
		db = db.Count(&total).Limit(req.PageSize).Offset((req.PageNo - 1) * req.PageSize)
	}

	// 执行查询
	err = db.
		Select(`node_reviewer_task.id,node_reviewer_task.comment,node_reviewer_task.status,node_reviewer_task.created_at,node_reviewer_task.updated_at,node_reviewer_task.reviewer_id,
                      node.id AS node_id,node.created_at AS node_created_at,
  				      workflow.id AS workflow_id,workflow.form_content, workflow.created_at AS workflow_created_at,
                      node_template.name AS node_name,
					  workflow_template.name AS workflow_name`).
		Find(&result).Error
	return
}

// QueryNodeReviewTasksTX 在事务中查询节点审批任务列表
// 支持按审批人、业务代码、业务ID、工作流ID等条件进行查询
func (w *NodeReviewTaskClient) QueryNodeReviewTasksTX(ctx context.Context, req aggregate.GetNodeReviewTasksRequest, tx *gorm.DB) (result []NodeReviewTasks, err error) {
	// 构建基础查询，先应用Scopes设置表和JOIN关系
	db := tx.WithContext(ctx).
		Scopes(NodeReviewerTaskView).
		Where("node_reviewer_task.status != ?", entity.TaskArchivedStatus).
		Order("node_reviewer_task.created_at DESC")

	if req.ReviewerID != "" {
		db = db.Where("node_reviewer_task.reviewer_id = ?", req.ReviewerID)
	}

	if req.BusinessCode != "" {
		db = db.Where("workflow.business_code = ?", req.BusinessCode)
	}

	if req.BusinessID != "" {
		db = db.Where("workflow.business_id = ?", req.BusinessID)
	}

	if req.WorkflowID != "" {
		db = db.Where("workflow.id = ?", req.WorkflowID)
	}

	// 执行查询
	err = db.
		Select(`node_reviewer_task.id,node_reviewer_task.comment,node_reviewer_task.status,node_reviewer_task.created_at,node_reviewer_task.updated_at,node_reviewer_task.reviewer_id,
                      node.id AS node_id,
  				      workflow.id AS workflow_id,workflow.form_content,
                      node_template.name AS node_name,
					  workflow_template.name AS workflow_name`).
		Find(&result).Error
	return
}

type NodeReviewTasks struct {
	ID                string    `gorm:"column:id;"`
	Comment           string    `gorm:"comment"`
	WorkflowID        string    `gorm:"workflow_id"`
	WorkflowName      string    `gorm:"workflow_name"`
	WorkflowCreatedAt time.Time `gorm:"workflow_created_at"`
	FormContent       string    `gorm:"form_content"`
	NodeID            string    `gorm:"node_id"`
	NodeName          string    `gorm:"node_name"`
	NodeCreatedAt     time.Time `gorm:"node_created_at"`
	Status            int       `gorm:"status"`
	ReviewerID        string    `gorm:"reviewer_id"`
	CreatedAt         time.Time `gorm:"created_at"`
	UpdatedAt         time.Time `gorm:"updated_at"`
}
